package protocol;

import java.io.BufferedReader;
import java.io.IOException;

public class ThreadReader extends Thread {

    private BufferedReader input = null;
    private StringBuffer readBuffer;
    private ThreadWorker mServer;

    public ThreadReader(BufferedReader _input, ThreadWorker _mServer) {
        this.input = _input;
        this.mServer = _mServer;
    }

    @Override
    public void run() {
        while (true) {
            try {
                mServer.receiveMessage(this.readMessage());

                //TODO : add to queue
            } catch (IOException ex) {
                mServer.closeConnection();
                return;
            } catch (Exception ex) {
                System.err.println("Reading from socket error: ");
                //ex.printStackTrace();
            }
        }

    }

    public Message readMessage() throws Exception {
        String line = input.readLine();
        if (line == null) {
            throw new IOException("Connection clossed");
        }
        int size = Integer.parseInt(line);
        char buffer[] = new char[size];
        //System.out.println(size);

        int nbReaded = 0;
        while (size > nbReaded) {
            int r = input.read(buffer, nbReaded, size - nbReaded);

            if (r == 0) {
                //TODO : connection clossed
                throw new IOException("Connection clossed");

            }
            nbReaded += r;
        }

        if (nbReaded < size) {
            throw new Exception("Error while reading from socket");
        }

        String command = new String(buffer);

        if (command == null) {
            throw new IOException("Socket clossed");
        }


        Message msg = Message.ParseMessageServer(command);

        return msg;
    }
}